﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Windows.Forms;
using System.Configuration;

namespace Client.Certificate
{
    internal class CertificateLoader
    {
        // Create client certificate:
        /*
         * makecert -n "CN=sMessengerClient_cln" -sky exchange -sv client.pvk client.cer
         * 
         * cert2spc client.cer client.spc
         * 
         * pvkimprt -PFX client.spc client.pvk
         * 
         * */


        public static X509Certificate2 GetClientCertificate(string password)
        {
            if (string.IsNullOrEmpty(password))
                return null;

            string pathAndFilename = Application.StartupPath + "\\Certificate\\" + ConfigurationSettings.AppSettings["certificateFilename"];

            if (!File.Exists(pathAndFilename))
                throw new FileNotFoundException("File not found: " + pathAndFilename);

            return new X509Certificate2(File.ReadAllBytes(pathAndFilename), password);
        }

        private static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
    }
}
